<?php


namespace app\admin\controller\jizhan;

use app\admin\model\HtnsActivity;
use app\admin\model\HtnsBasestationStore;
use app\admin\model\HtnsSystemCity;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use jianyan\excel\Excel;
use think\App;
use think\facade\Cache;

/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="基站-海淘女神-用户列表")
 */
class HtnsUser extends AdminController
{

    use Curd;

    public $jmycGrade;
    public $storeList;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->sort = [
            'uid' => 'desc',
        ];
        $this->model = new \app\admin\model\HtnsUser();
        $jmycGrade = $this->model->gradeLevel;
        $this->jmycGrade = $jmycGrade;
        $this->assign('gradeList',$jmycGrade);

        $whereS['delete_time'] = 0;
        $stores = HtnsBasestationStore::where($whereS)->order('id desc')->select()->toArray();
        $storeList = array_column($stores,'name','id');
        $this->storeList = $storeList;
        $this->assign('storeList',$storeList);
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index($export = 0)
    {
        if ($this->request->isAjax() || $export) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 自定义搜索条件解析
            $whereArr = [];
            $filter   = input('filter');
            $filter = htmlspecialchars_decode($filter);// html特殊字符转化&quot;转换为'
            if ($filter) {
                $filterArr = json_decode($filter, true);
                if (isset($filterArr['uid'])) {
                    $whereArr[] = ['uid', '=', $filterArr['uid']];
                }
                if (isset($filterArr['real_name'])) {
                    $whereArr[] = ['real_name', 'like', '%'.$filterArr['real_name'].'%'];
                }
                if (isset($filterArr['nickname'])) {
                    $whereArr[] = ['nickname', 'like', '%'.$filterArr['nickname'].'%'];
                }
                if (isset($filterArr['phone'])) {
                    $whereArr[] = ['phone', 'like', '%'.$filterArr['phone'].'%'];
                }
                if (isset($filterArr['spread_user'])) {
                    $whereO[] = ['phone' , 'like' , '%'.$filterArr['spread_user'].'%'];
                    $spreadUid = $this->model->where($whereO)->value('uid');
                    if($spreadUid){
                        $whereArr[] = ['spread_uid', '=', $spreadUid];
                    }
                }
                if (isset($filterArr['store_info'])) {
                    $whereArr[] = ['store_id', '=', $filterArr['store_info']];
                }
                if (isset($filterArr['status'])) {
                    $whereArr[] = ['status', '=', $filterArr['status']];
                }
                if (isset($filterArr['add_time'])) {
                    $time       = explode(' - ', $filterArr['add_time']);
                    $whereArr[] = ['add_time', 'between', [strtotime($time[0]), strtotime($time[1])]];
                }
            }
            if ($export) {
                $page  = 1;
                $limit = 10000;
            }
            $count = $this->model
                ->where($whereArr)
                ->count();
            $list  = $this->model
                ->where($whereArr)
                ->page($page, $limit)
                ->order($this->sort)
                ->select()->toArray();
            foreach ($list as &$v) {
                $v['id'] = $v['uid'];
                $v['jmyc_grade'] = isset($this->jmycGrade[$v['jmyc_grade']]) ? $this->jmycGrade[$v['jmyc_grade']] : '普通用户';
//                echo 'jmyc_grade<pre>';print_r($this->jmycGrade[$v['jmyc_grade']]);die;
                $v['spread_user'] = '';
                $v['store_info'] = '';
                if($v['spread_uid']){
                    $parent = $this->model->find($v['spread_uid']);
                    $jmyc_grade = isset($this->jmycGrade[$parent['jmyc_grade']]) ? $this->jmycGrade[$parent['jmyc_grade']] : '普通用户';
                    $v['spread_user'] = $parent['uid'].'|'.$parent['phone'].'|'.$parent['real_name'].'|'.$jmyc_grade;
                }
                if(isset($this->storeList[$v['store_id']])){
                    $v['store_info'] = $this->storeList[$v['store_id']];
                }
                $v['add_time'] = empty($v['add_time']) ? '':date('Y-m-d H:i:s',$v['add_time']);
            }
            // 导出
            if ($export) {
                return $list;
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $post['pwd'] = md5($post['pwd']);
                $post['avatar']   = 'https://store.htnsvip.com/uploads/attach/2023/02/20230228/775ca580e6d8d85ece0560e52910ccf0.png';//默认logo为头像
                $post['user_type'] = 'h5';
                $post['add_time'] = time();
                $save               = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $post['pwd'] = md5($post['pwd']);
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        $header = [
            ['用户Id','uid'],
            ['姓名','real_name'],
            ['昵称','nickname'],
            ['等级','jmyc_grade'],
            ['手机号','phone'],
            ['余额','now_money'],
            ['积分','integral'],
            ['上级推广人信息','spread_user'],
            ['所在门店','store_info'],
            ['状态','status'],
            ['备注说明','mark'],
            ['添加时间','add_time'],
        ];
        $list = $this->index(1);

        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }
}